package top.codedance.iotp.client.manage.net.listenner;

import cd.io.netty.channel.ChannelFuture;
import cd.io.netty.channel.ChannelFutureListener;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.client.manage.ManageApplication;
import top.codedance.iotp.client.manage.net.Manage;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.entity.CommonEntity;
import org.apache.log4j.Logger;

import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;

public class ConnectionListener implements ChannelFutureListener {

    private static Logger logger = ManageApplication.getLogger(ConnectionListener.class);
    private Manage manage;

    public ConnectionListener(Manage manage){
        this.manage = manage;
    }

    public void operationComplete(final ChannelFuture future) {
        if (future.isSuccess() && future.channel().isActive()) {
            logger.debug("Connect the server success");
            if(ManageApplication.isAutoUpdate) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if(!future.channel().isActive()){
                            timer.cancel();
                        }
                        if(!ManageApplication.isUpgrading()) {
                            try {
                                CommonEntity commonEntity = new CommonEntity();
                                commonEntity.setCommand(Command.UPGRADE);
                                commonEntity.setBody(ManageApplication.getVersion().toString().getBytes());
                                future.channel().writeAndFlush(commonEntity);
                                logger.debug("Request upgrade");
                            }catch (Exception e){
                                logger.debug(e.getMessage());
                            }
                        }
                    }
                }, 1000l, 1000l * 60);
            }

            Timer timer2 = new Timer();
            timer2.schedule(new TimerTask() {
                @Override
                public void run() {
                    if(!future.channel().isActive()){
                        timer2.cancel();
                    }
                    try {
                        CommonEntity commonEntity = new CommonEntity();
                        commonEntity.setCommand(Command.GET_LOAD);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("deviceId", ManageApplication.DEVICE_ID);
                        commonEntity.setBody(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
                        future.channel().writeAndFlush(commonEntity);
                        ManageApplication.loadRequestCount++;
                        logger.debug("Get Load, loadRequestCount: " + ManageApplication.loadRequestCount);
                    }catch (Exception e){
                        logger.debug(e.getMessage());
                    }
                    if(ManageApplication.loadRequestCount >= 3){
                        ManageApplication.clientRunner.exec(("{\"plugin\":4,\"client\":{\"isExceptionExit\":true,\"amount\":1}}\n").getBytes(StandardCharsets.UTF_8));
                        ManageApplication.p.destroyForcibly();
                        ManageApplication.clientFuture.cancel(true);
                        ManageApplication.loadRequestCount = 0;
                    }
                }
            }, 1000l * 60, 1000l * 60);
        }else{
            future.cancel(true);
        }
    }
}
